{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "t09eeeR5prIJ"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "GCCk8_dHpuNf"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ovpZyIhNIgoq"
      },
      "source": [
        "# Text generation with an RNN"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hcD2nPQvPOFM"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/text/tutorials/text_generation\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/text/blob/master/docs/tutorials/text_generation.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/text/blob/master/docs/tutorials/text_generation.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/text/docs/tutorials/text_generation.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BwpJ5IffzRG6"
      },
      "source": [
        "This tutorial demonstrates how to generate text using a character-based RNN. You will work with a dataset of Shakespeare's writing from Andrej Karpathy's [The Unreasonable Effectiveness of Recurrent Neural Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness/). Given a sequence of characters from this data (\"Shakespear\"), train a model to predict the next character in the sequence (\"e\"). Longer sequences of text can be generated by calling the model repeatedly.\n",
        "\n",
        "Note: Enable GPU acceleration to execute this notebook faster. In Colab: *Runtime \u003e Change runtime type \u003e Hardware accelerator \u003e GPU*.\n",
        "\n",
        "This tutorial includes runnable code implemented using [tf.keras](https://www.tensorflow.org/guide/keras/sequential_model) and [eager execution](https://www.tensorflow.org/guide/eager). The following is the sample output when the model in this tutorial trained for 30 epochs, and started with the prompt \"Q\":"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HcygKkEVZBaa"
      },
      "source": [
        "\u003cpre\u003e\n",
        "QUEENE:\n",
        "I had thought thou hadst a Roman; for the oracle,\n",
        "Thus by All bids the man against the word,\n",
        "Which are so weak of care, by old care done;\n",
        "Your children were in your holy love,\n",
        "And the precipitation through the bleeding throne.\n",
        "\n",
        "BISHOP OF ELY:\n",
        "Marry, and will, my lord, to weep in such a one were prettiest;\n",
        "Yet now I was adopted heir\n",
        "Of the world's lamentable day,\n",
        "To watch the next way with his father with his face?\n",
        "\n",
        "ESCALUS:\n",
        "The cause why then we are all resolved more sons.\n",
        "\n",
        "VOLUMNIA:\n",
        "O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,\n",
        "And love and pale as any will to that word.\n",
        "\n",
        "QUEEN ELIZABETH:\n",
        "But how long have I heard the soul for this world,\n",
        "And show his hands of life be proved to stand.\n",
        "\n",
        "PETRUCHIO:\n",
        "I say he look'd on, if I must be content\n",
        "To stay him from the fatal of our country's bliss.\n",
        "His lordship pluck'd from this sentence then for prey,\n",
        "And then let us twain, being the moon,\n",
        "were she such a case as fills m\n",
        "\u003c/pre\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_bGsCP9DZFQ5"
      },
      "source": [
        "While some of the sentences are grammatical, most do not make sense. The model has not learned the meaning of words, but consider:\n",
        "\n",
        "* The model is character-based. When training started, the model did not know how to spell an English word, or that words were even a unit of text.\n",
        "\n",
        "* The structure of the output resembles a play—blocks of text generally begin with a speaker name, in all capital letters similar to the dataset.\n",
        "\n",
        "* As demonstrated below, the model is trained on small batches of text (100 characters each), and is still able to generate a longer sequence of text with coherent structure."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "srXC6pLGLwS6"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WGyKZj3bzf9p"
      },
      "source": [
        "### Import TensorFlow and other libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yG_n40gFzf9s"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "from tensorflow.keras.layers.experimental import preprocessing\n",
        "\n",
        "import numpy as np\n",
        "import os\n",
        "import time"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EHDoRoc5PKWz"
      },
      "source": [
        "### Download the Shakespeare dataset\n",
        "\n",
        "Change the following line to run this code on your own data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pD_55cOxLkAb"
      },
      "outputs": [],
      "source": [
        "path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UHjdCjDuSvX_"
      },
      "source": [
        "### Read the data\n",
        "\n",
        "First, look in the text:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aavnuByVymwK"
      },
      "outputs": [],
      "source": [
        "# Read, then decode for py2 compat.\n",
        "text = open(path_to_file, 'rb').read().decode(encoding='utf-8')\n",
        "# length of text is the number of characters in it\n",
        "print(f'Length of text: {len(text)} characters')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Duhg9NrUymwO"
      },
      "outputs": [],
      "source": [
        "# Take a look at the first 250 characters in text\n",
        "print(text[:250])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IlCgQBRVymwR"
      },
      "outputs": [],
      "source": [
        "# The unique characters in the file\n",
        "vocab = sorted(set(text))\n",
        "print(f'{len(vocab)} unique characters')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rNnrKn_lL-IJ"
      },
      "source": [
        "## Process the text"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LFjSVAlWzf-N"
      },
      "source": [
        "### Vectorize the text\n",
        "\n",
        "Before training, you need to convert the strings to a numerical representation. \n",
        "\n",
        "The `preprocessing.StringLookup` layer can convert each character into a numeric ID. It just needs the text to be split into tokens first."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "a86OoYtO01go"
      },
      "outputs": [],
      "source": [
        "example_texts = ['abcdefg', 'xyz']\n",
        "\n",
        "chars = tf.strings.unicode_split(example_texts, input_encoding='UTF-8')\n",
        "chars"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1s4f1q3iqY8f"
      },
      "source": [
        "Now create the `preprocessing.StringLookup` layer:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6GMlCe3qzaL9"
      },
      "outputs": [],
      "source": [
        "ids_from_chars = preprocessing.StringLookup(\n",
        "    vocabulary=list(vocab), mask_token=None)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZmX_jbgQqfOi"
      },
      "source": [
        "It converts form tokens to character IDs:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WLv5Q_2TC2pc"
      },
      "outputs": [],
      "source": [
        "ids = ids_from_chars(chars)\n",
        "ids"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tZfqhkYCymwX"
      },
      "source": [
        "Since the goal of this tutorial is to generate text, it will also be important to invert this representation and recover human-readable strings from it. For this you can use `preprocessing.StringLookup(..., invert=True)`.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uenivzwqsDhp"
      },
      "source": [
        "Note: Here instead of passing the original vocabulary generated with `sorted(set(text))` use the `get_vocabulary()` method of the `preprocessing.StringLookup` layer so that the `[UNK]` tokens is set the same way."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Wd2m3mqkDjRj"
      },
      "outputs": [],
      "source": [
        "chars_from_ids = tf.keras.layers.experimental.preprocessing.StringLookup(\n",
        "    vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pqTDDxS-s-H8"
      },
      "source": [
        "This layer recovers the characters from the vectors of IDs, and returns them as a `tf.RaggedTensor` of characters:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "c2GCh0ySD44s"
      },
      "outputs": [],
      "source": [
        "chars = chars_from_ids(ids)\n",
        "chars"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-FeW5gqutT3o"
      },
      "source": [
        "You can `tf.strings.reduce_join` to join the characters back into strings. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zxYI-PeltqKP"
      },
      "outputs": [],
      "source": [
        "tf.strings.reduce_join(chars, axis=-1).numpy()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "w5apvBDn9Ind"
      },
      "outputs": [],
      "source": [
        "def text_from_ids(ids):\n",
        "  return tf.strings.reduce_join(chars_from_ids(ids), axis=-1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bbmsf23Bymwe"
      },
      "source": [
        "### The prediction task"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wssHQ1oGymwe"
      },
      "source": [
        "Given a character, or a sequence of characters, what is the most probable next character? This is the task you're training the model to perform. The input to the model will be a sequence of characters, and you train the model to predict the output—the following character at each time step.\n",
        "\n",
        "Since RNNs maintain an internal state that depends on the previously seen elements, given all the characters computed until this moment, what is the next character?\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hgsVvVxnymwf"
      },
      "source": [
        "### Create training examples and targets\n",
        "\n",
        "Next divide the text into example sequences. Each input sequence will contain `seq_length` characters from the text.\n",
        "\n",
        "For each input sequence, the corresponding targets contain the same length of text, except shifted one character to the right.\n",
        "\n",
        "So break the text into chunks of `seq_length+1`. For example, say `seq_length` is 4 and our text is \"Hello\". The input sequence would be \"Hell\", and the target sequence \"ello\".\n",
        "\n",
        "To do this first use the `tf.data.Dataset.from_tensor_slices` function to convert the text vector into a stream of character indices."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UopbsKi88tm5"
      },
      "outputs": [],
      "source": [
        "all_ids = ids_from_chars(tf.strings.unicode_split(text, 'UTF-8'))\n",
        "all_ids"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qmxrYDCTy-eL"
      },
      "outputs": [],
      "source": [
        "ids_dataset = tf.data.Dataset.from_tensor_slices(all_ids)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cjH5v45-yqqH"
      },
      "outputs": [],
      "source": [
        "for ids in ids_dataset.take(10):\n",
        "    print(chars_from_ids(ids).numpy().decode('utf-8'))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "C-G2oaTxy6km"
      },
      "outputs": [],
      "source": [
        "seq_length = 100\n",
        "examples_per_epoch = len(text)//(seq_length+1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-ZSYAcQV8OGP"
      },
      "source": [
        "The `batch` method lets you easily convert these individual characters to sequences of the desired size."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BpdjRO2CzOfZ"
      },
      "outputs": [],
      "source": [
        "sequences = ids_dataset.batch(seq_length+1, drop_remainder=True)\n",
        "\n",
        "for seq in sequences.take(1):\n",
        "  print(chars_from_ids(seq))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5PHW902-4oZt"
      },
      "source": [
        "It's easier to see what this is doing if you join the tokens back into strings:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "QO32cMWu4a06"
      },
      "outputs": [],
      "source": [
        "for seq in sequences.take(5):\n",
        "  print(text_from_ids(seq).numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UbLcIPBj_mWZ"
      },
      "source": [
        "For training you'll need a dataset of `(input, label)` pairs. Where `input` and \n",
        "`label` are sequences. At each time step the input is the current character and the label is the next character. \n",
        "\n",
        "Here's a function that takes a sequence as input, duplicates, and shifts it to align the input and label for each timestep:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9NGu-FkO_kYU"
      },
      "outputs": [],
      "source": [
        "def split_input_target(sequence):\n",
        "    input_text = sequence[:-1]\n",
        "    target_text = sequence[1:]\n",
        "    return input_text, target_text"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WxbDTJTw5u_P"
      },
      "outputs": [],
      "source": [
        "split_input_target(list(\"Tensorflow\"))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "B9iKPXkw5xwa"
      },
      "outputs": [],
      "source": [
        "dataset = sequences.map(split_input_target)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GNbw-iR0ymwj"
      },
      "outputs": [],
      "source": [
        "for input_example, target_example in dataset.take(1):\n",
        "    print(\"Input :\", text_from_ids(input_example).numpy())\n",
        "    print(\"Target:\", text_from_ids(target_example).numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MJdfPmdqzf-R"
      },
      "source": [
        "### Create training batches\n",
        "\n",
        "You used `tf.data` to split the text into manageable sequences. But before feeding this data into the model, you need to shuffle the data and pack it into batches."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "p2pGotuNzf-S"
      },
      "outputs": [],
      "source": [
        "# Batch size\n",
        "BATCH_SIZE = 64\n",
        "\n",
        "# Buffer size to shuffle the dataset\n",
        "# (TF data is designed to work with possibly infinite sequences,\n",
        "# so it doesn't attempt to shuffle the entire sequence in memory. Instead,\n",
        "# it maintains a buffer in which it shuffles elements).\n",
        "BUFFER_SIZE = 10000\n",
        "\n",
        "dataset = (\n",
        "    dataset\n",
        "    .shuffle(BUFFER_SIZE)\n",
        "    .batch(BATCH_SIZE, drop_remainder=True)\n",
        "    .prefetch(tf.data.experimental.AUTOTUNE))\n",
        "\n",
        "dataset"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "r6oUuElIMgVx"
      },
      "source": [
        "## Build The Model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m8gPwEjRzf-Z"
      },
      "source": [
        "This section defines the model as a `keras.Model` subclass (For details see [Making new Layers and Models via subclassing](https://www.tensorflow.org/guide/keras/custom_layers_and_models)). \n",
        "\n",
        "This model has three layers:\n",
        "\n",
        "* `tf.keras.layers.Embedding`: The input layer. A trainable lookup table that will map each character-ID to a vector with `embedding_dim` dimensions;\n",
        "* `tf.keras.layers.GRU`: A type of RNN with size `units=rnn_units` (You can also use an LSTM layer here.)\n",
        "* `tf.keras.layers.Dense`: The output layer, with `vocab_size` outputs. It outputs one logit for each character in the vocabulary. These are the log-likelihood of each character according to the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zHT8cLh7EAsg"
      },
      "outputs": [],
      "source": [
        "# Length of the vocabulary in chars\n",
        "vocab_size = len(vocab)\n",
        "\n",
        "# The embedding dimension\n",
        "embedding_dim = 256\n",
        "\n",
        "# Number of RNN units\n",
        "rnn_units = 1024"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wj8HQ2w8z4iO"
      },
      "outputs": [],
      "source": [
        "class MyModel(tf.keras.Model):\n",
        "  def __init__(self, vocab_size, embedding_dim, rnn_units):\n",
        "    super().__init__(self)\n",
        "    self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n",
        "    self.gru = tf.keras.layers.GRU(rnn_units,\n",
        "                                   return_sequences=True,\n",
        "                                   return_state=True)\n",
        "    self.dense = tf.keras.layers.Dense(vocab_size)\n",
        "\n",
        "  def call(self, inputs, states=None, return_state=False, training=False):\n",
        "    x = inputs\n",
        "    x = self.embedding(x, training=training)\n",
        "    if states is None:\n",
        "      states = self.gru.get_initial_state(x)\n",
        "    x, states = self.gru(x, initial_state=states, training=training)\n",
        "    x = self.dense(x, training=training)\n",
        "\n",
        "    if return_state:\n",
        "      return x, states\n",
        "    else:\n",
        "      return x"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IX58Xj9z47Aw"
      },
      "outputs": [],
      "source": [
        "model = MyModel(\n",
        "    # Be sure the vocabulary size matches the `StringLookup` layers.\n",
        "    vocab_size=len(ids_from_chars.get_vocabulary()),\n",
        "    embedding_dim=embedding_dim,\n",
        "    rnn_units=rnn_units)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RkA5upJIJ7W7"
      },
      "source": [
        "For each character the model looks up the embedding, runs the GRU one timestep with the embedding as input, and applies the dense layer to generate logits predicting the log-likelihood of the next character:\n",
        "\n",
        "![A drawing of the data passing through the model](images/text_generation_training.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gKbfm04amhXk"
      },
      "source": [
        "Note: For training you could use a `keras.Sequential` model here. To  generate text later you'll need to manage the RNN's internal state. It's simpler to include the state input and output options upfront, than it is to rearrange the model architecture later. For more details see the [Keras RNN guide](https://www.tensorflow.org/guide/keras/rnn#rnn_state_reuse)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-ubPo0_9Prjb"
      },
      "source": [
        "## Try the model\n",
        "\n",
        "Now run the model to see that it behaves as expected.\n",
        "\n",
        "First check the shape of the output:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "C-_70kKAPrPU"
      },
      "outputs": [],
      "source": [
        "for input_example_batch, target_example_batch in dataset.take(1):\n",
        "    example_batch_predictions = model(input_example_batch)\n",
        "    print(example_batch_predictions.shape, \"# (batch_size, sequence_length, vocab_size)\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Q6NzLBi4VM4o"
      },
      "source": [
        "In the above example the sequence length of the input is `100` but the model can be run on inputs of any length:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vPGmAAXmVLGC"
      },
      "outputs": [],
      "source": [
        "model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uwv0gEkURfx1"
      },
      "source": [
        "To get actual predictions from the model you need to sample from the output distribution, to get actual character indices. This distribution is defined by the logits over the character vocabulary.\n",
        "\n",
        "Note: It is important to _sample_ from this distribution as taking the _argmax_ of the distribution can easily get the model stuck in a loop.\n",
        "\n",
        "Try it for the first example in the batch:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4V4MfFg0RQJg"
      },
      "outputs": [],
      "source": [
        "sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)\n",
        "sampled_indices = tf.squeeze(sampled_indices, axis=-1).numpy()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QM1Vbxs_URw5"
      },
      "source": [
        "This gives us, at each timestep, a prediction of the next character index:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YqFMUQc_UFgM"
      },
      "outputs": [],
      "source": [
        "sampled_indices"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LfLtsP3mUhCG"
      },
      "source": [
        "Decode these to see the text predicted by this untrained model:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xWcFwPwLSo05"
      },
      "outputs": [],
      "source": [
        "print(\"Input:\\n\", text_from_ids(input_example_batch[0]).numpy())\n",
        "print()\n",
        "print(\"Next Char Predictions:\\n\", text_from_ids(sampled_indices).numpy())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LJL0Q0YPY6Ee"
      },
      "source": [
        "## Train the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YCbHQHiaa4Ic"
      },
      "source": [
        "At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "trpqTWyvk0nr"
      },
      "source": [
        "### Attach an optimizer, and a loss function"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UAjbjY03eiQ4"
      },
      "source": [
        "The standard `tf.keras.losses.sparse_categorical_crossentropy` loss function works in this case because it is applied across the last dimension of the predictions.\n",
        "\n",
        "Because your model returns logits, you need to set the `from_logits` flag.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZOeWdgxNFDXq"
      },
      "outputs": [],
      "source": [
        "loss = tf.losses.SparseCategoricalCrossentropy(from_logits=True)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4HrXTACTdzY-"
      },
      "outputs": [],
      "source": [
        "example_batch_loss = loss(target_example_batch, example_batch_predictions)\n",
        "mean_loss = example_batch_loss.numpy().mean()\n",
        "print(\"Prediction shape: \", example_batch_predictions.shape, \" # (batch_size, sequence_length, vocab_size)\")\n",
        "print(\"Mean loss:        \", mean_loss)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vkvUIneTFiow"
      },
      "source": [
        "A newly initialized model shouldn't be too sure of itself, the output logits should all have similar magnitudes. To confirm this you can check that the exponential of the mean loss is approximately equal to the vocabulary size. A much higher loss means the model is sure of its wrong answers, and is badly initialized:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "MAJfS5YoFiHf"
      },
      "outputs": [],
      "source": [
        "tf.exp(mean_loss).numpy()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jeOXriLcymww"
      },
      "source": [
        "Configure the training procedure using the `tf.keras.Model.compile` method. Use `tf.keras.optimizers.Adam` with default arguments and the loss function."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DDl1_Een6rL0"
      },
      "outputs": [],
      "source": [
        "model.compile(optimizer='adam', loss=loss)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ieSJdchZggUj"
      },
      "source": [
        "### Configure checkpoints"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "C6XBUUavgF56"
      },
      "source": [
        "Use a `tf.keras.callbacks.ModelCheckpoint` to ensure that checkpoints are saved during training:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "W6fWTriUZP-n"
      },
      "outputs": [],
      "source": [
        "# Directory where the checkpoints will be saved\n",
        "checkpoint_dir = './training_checkpoints'\n",
        "# Name of the checkpoint files\n",
        "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt_{epoch}\")\n",
        "\n",
        "checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n",
        "    filepath=checkpoint_prefix,\n",
        "    save_weights_only=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3Ky3F_BhgkTW"
      },
      "source": [
        "### Execute the training"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IxdOA-rgyGvs"
      },
      "source": [
        "To keep training time reasonable, use 10 epochs to train the model. In Colab, set the runtime to GPU for faster training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7yGBE2zxMMHs"
      },
      "outputs": [],
      "source": [
        "EPOCHS = 20"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "UK-hmKjYVoll"
      },
      "outputs": [],
      "source": [
        "history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kKkD5M6eoSiN"
      },
      "source": [
        "## Generate text"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oIdQ8c8NvMzV"
      },
      "source": [
        "The simplest way to generate text with this model is to run it in a loop, and keep track of the model's internal state as you execute it.\n",
        "\n",
        "![To generate text the model's output is fed back to the input](images/text_generation_sampling.png)\n",
        "\n",
        "Each time you call the model you pass in some text and an internal state. The model returns a prediction for the next character and its new state. Pass the prediction and state back in to continue generating text.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DjGz1tDkzf-u"
      },
      "source": [
        "The following makes a single step prediction:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iSBU1tHmlUSs"
      },
      "outputs": [],
      "source": [
        "class OneStep(tf.keras.Model):\n",
        "  def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):\n",
        "    super().__init__()\n",
        "    self.temperature = temperature\n",
        "    self.model = model\n",
        "    self.chars_from_ids = chars_from_ids\n",
        "    self.ids_from_chars = ids_from_chars\n",
        "\n",
        "    # Create a mask to prevent \"[UNK]\" from being generated.\n",
        "    skip_ids = self.ids_from_chars(['[UNK]'])[:, None]\n",
        "    sparse_mask = tf.SparseTensor(\n",
        "        # Put a -inf at each bad index.\n",
        "        values=[-float('inf')]*len(skip_ids),\n",
        "        indices=skip_ids,\n",
        "        # Match the shape to the vocabulary\n",
        "        dense_shape=[len(ids_from_chars.get_vocabulary())])\n",
        "    self.prediction_mask = tf.sparse.to_dense(sparse_mask)\n",
        "\n",
        "  @tf.function\n",
        "  def generate_one_step(self, inputs, states=None):\n",
        "    # Convert strings to token IDs.\n",
        "    input_chars = tf.strings.unicode_split(inputs, 'UTF-8')\n",
        "    input_ids = self.ids_from_chars(input_chars).to_tensor()\n",
        "\n",
        "    # Run the model.\n",
        "    # predicted_logits.shape is [batch, char, next_char_logits]\n",
        "    predicted_logits, states = self.model(inputs=input_ids, states=states,\n",
        "                                          return_state=True)\n",
        "    # Only use the last prediction.\n",
        "    predicted_logits = predicted_logits[:, -1, :]\n",
        "    predicted_logits = predicted_logits/self.temperature\n",
        "    # Apply the prediction mask: prevent \"[UNK]\" from being generated.\n",
        "    predicted_logits = predicted_logits + self.prediction_mask\n",
        "\n",
        "    # Sample the output logits to generate token IDs.\n",
        "    predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)\n",
        "    predicted_ids = tf.squeeze(predicted_ids, axis=-1)\n",
        "\n",
        "    # Convert from token ids to characters\n",
        "    predicted_chars = self.chars_from_ids(predicted_ids)\n",
        "\n",
        "    # Return the characters and model state.\n",
        "    return predicted_chars, states"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fqMOuDutnOxK"
      },
      "outputs": [],
      "source": [
        "one_step_model = OneStep(model, chars_from_ids, ids_from_chars)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "p9yDoa0G3IgQ"
      },
      "source": [
        "Run it in a loop to generate some text. Looking at the generated text, you'll see the model knows when to capitalize, make paragraphs and imitates a Shakespeare-like writing vocabulary. With the small number of training epochs, it has not yet learned to form coherent sentences."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ST7PSyk9t1mT"
      },
      "outputs": [],
      "source": [
        "start = time.time()\n",
        "states = None\n",
        "next_char = tf.constant(['ROMEO:'])\n",
        "result = [next_char]\n",
        "\n",
        "for n in range(1000):\n",
        "  next_char, states = one_step_model.generate_one_step(next_char, states=states)\n",
        "  result.append(next_char)\n",
        "\n",
        "result = tf.strings.join(result)\n",
        "end = time.time()\n",
        "print(result[0].numpy().decode('utf-8'), '\\n\\n' + '_'*80)\n",
        "print('\\nRun time:', end - start)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AM2Uma_-yVIq"
      },
      "source": [
        "The easiest thing you can do to improve the results is to train it for longer (try `EPOCHS = 30`).\n",
        "\n",
        "You can also experiment with a different start string, try adding another RNN layer to improve the model's accuracy, or adjust the temperature parameter to generate more or less random predictions."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_OfbI4aULmuj"
      },
      "source": [
        "If you want the model to generate text *faster* the easiest thing you can do is batch the text generation. In the example below the model generates 5 outputs in about the same time it took to generate 1 above. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZkLu7Y8UCMT7"
      },
      "outputs": [],
      "source": [
        "start = time.time()\n",
        "states = None\n",
        "next_char = tf.constant(['ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:'])\n",
        "result = [next_char]\n",
        "\n",
        "for n in range(1000):\n",
        "  next_char, states = one_step_model.generate_one_step(next_char, states=states)\n",
        "  result.append(next_char)\n",
        "\n",
        "result = tf.strings.join(result)\n",
        "end = time.time()\n",
        "print(result, '\\n\\n' + '_'*80)\n",
        "print('\\nRun time:', end - start)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UlUQzwu6EXam"
      },
      "source": [
        "## Export the generator\n",
        "\n",
        "This single-step model can easily be [saved and restored](https://www.tensorflow.org/guide/saved_model), allowing you to use it anywhere a `tf.saved_model` is accepted."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3Grk32H_CzsC"
      },
      "outputs": [],
      "source": [
        "tf.saved_model.save(one_step_model, 'one_step')\n",
        "one_step_reloaded = tf.saved_model.load('one_step')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_Z9bb_wX6Uuu"
      },
      "outputs": [],
      "source": [
        "states = None\n",
        "next_char = tf.constant(['ROMEO:'])\n",
        "result = [next_char]\n",
        "\n",
        "for n in range(100):\n",
        "  next_char, states = one_step_reloaded.generate_one_step(next_char, states=states)\n",
        "  result.append(next_char)\n",
        "\n",
        "print(tf.strings.join(result)[0].numpy().decode(\"utf-8\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y4QwTjAM6A2O"
      },
      "source": [
        "## Advanced: Customized Training\n",
        "\n",
        "The above training procedure is simple, but does not give you much control.\n",
        "It uses teacher-forcing which prevents bad predictions from being fed back to the model, so the model never learns to recover from mistakes.\n",
        "\n",
        "So now that you've seen how to run the model manually next you'll implement the training loop. This gives a starting point if, for example, you want to implement _curriculum  learning_ to help stabilize the model's open-loop output.\n",
        "\n",
        "The most important part of a custom training loop is the train step function.\n",
        "\n",
        "Use `tf.GradientTape` to track the gradients. You can learn more about this approach by reading the [eager execution guide](https://www.tensorflow.org/guide/eager).\n",
        "\n",
        "The basic procedure is:\n",
        "\n",
        "1. Execute the model and calculate the loss under a `tf.GradientTape`.\n",
        "2. Calculate the updates and apply them to the model using the optimizer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "x0pZ101hjwW0"
      },
      "outputs": [],
      "source": [
        "class CustomTraining(MyModel):\n",
        "  @tf.function\n",
        "  def train_step(self, inputs):\n",
        "      inputs, labels = inputs\n",
        "      with tf.GradientTape() as tape:\n",
        "          predictions = self(inputs, training=True)\n",
        "          loss = self.loss(labels, predictions)\n",
        "      grads = tape.gradient(loss, model.trainable_variables)\n",
        "      self.optimizer.apply_gradients(zip(grads, model.trainable_variables))\n",
        "\n",
        "      return {'loss': loss}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4Oc-eJALcK8B"
      },
      "source": [
        "The above implementation of the `train_step` method follows [Keras' `train_step` conventions](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit). This is optional, but it allows you to change the behavior of the train step and still use keras' `Model.compile` and `Model.fit` methods."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XKyWiZ_Lj7w5"
      },
      "outputs": [],
      "source": [
        "model = CustomTraining(\n",
        "    vocab_size=len(ids_from_chars.get_vocabulary()),\n",
        "    embedding_dim=embedding_dim,\n",
        "    rnn_units=rnn_units)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "U817KUm7knlm"
      },
      "outputs": [],
      "source": [
        "model.compile(optimizer = tf.keras.optimizers.Adam(),\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "o694aoBPnEi9"
      },
      "outputs": [],
      "source": [
        "model.fit(dataset, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "W8nAtKHVoInR"
      },
      "source": [
        "Or if you need more control, you can write your own complete custom training loop:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "d4tSNwymzf-q"
      },
      "outputs": [],
      "source": [
        "EPOCHS = 10\n",
        "\n",
        "mean = tf.metrics.Mean()\n",
        "\n",
        "for epoch in range(EPOCHS):\n",
        "    start = time.time()\n",
        "\n",
        "    mean.reset_states()\n",
        "    for (batch_n, (inp, target)) in enumerate(dataset):\n",
        "        logs = model.train_step([inp, target])\n",
        "        mean.update_state(logs['loss'])\n",
        "\n",
        "        if batch_n % 50 == 0:\n",
        "            template = f\"Epoch {epoch+1} Batch {batch_n} Loss {logs['loss']:.4f}\"\n",
        "            print(template)\n",
        "\n",
        "    # saving (checkpoint) the model every 5 epochs\n",
        "    if (epoch + 1) % 5 == 0:\n",
        "        model.save_weights(checkpoint_prefix.format(epoch=epoch))\n",
        "\n",
        "    print()\n",
        "    print(f'Epoch {epoch+1} Loss: {mean.result().numpy():.4f}')\n",
        "    print(f'Time taken for 1 epoch {time.time() - start:.2f} sec')\n",
        "    print(\"_\"*80)\n",
        "\n",
        "model.save_weights(checkpoint_prefix.format(epoch=epoch))"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "text_generation.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
